#coding=utf8

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import UserProfile, SmsHist, Company, UserJob, Department, CustomerProfile
from django.contrib import auth
from rest_framework.decorators import api_view, detail_route, list_route, permission_classes, authentication_classes
from rest_framework.views import APIView
from helper import *
from django.utils import timezone
import datetime
from .serializers import UserProfileSerializer, RegionSerializer, CompanySerializer, UserJobSerializer, DepartmentSerializer, CustomerProfileSerializer
from .permissions import IsUserAuthenticated
from rest_framework.authtoken.models import Token
from myviewset import *
from django.db.models import Q

# Create your views here.


class CustomBackend(ModelBackend):
    """扩展用户登陆，使用邮箱、用户名、手机号进行登陆"""

    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(isEnable = True) & (Q(username=username) | Q(email=username) | Q(mobile=username)))
            if user.check_password(password):
                return user
        except Exception as e:
            return None





@api_view(['POST'])
def UserRegister(request):
    """
    用户注册：参数mobile 手机号 , password 密码 , code 验证码
    """
    postdata = request.data
    if not postdata.has_key("mobile"):
        return res(-1, u"请输入手机号！")
    if not phonecheck(postdata["mobile"]):
        return res(-1, u"手机号无效！")
    if not postdata.has_key("password"):
        return res(-1, u"请输入密码！")
    if not passwordcheck(postdata["password"]):
        return res(-1, u"密码无效")
    if not postdata.has_key("code"):
        return res(-1, u"请输入验证码！")
    if len(postdata["code"]) == 0:
        return res(-1, u"验证码无效！")

    queryset = UserProfile.objects.filter(username=postdata["mobile"])
    if queryset.exists():
        return res(-1, u"此手机号已被注册！")
    else:
        """校验验证码"""
        starttime = timezone.now() - datetime.timedelta(minutes = 3)
        queryset_code = SmsHist.objects.filter(mobile=postdata["mobile"]).\
            filter(timestamp__gt=starttime).\
            filter(codestr=postdata["code"].upper())

        if queryset_code.exists():
            """注册"""
            u = UserProfile(mobile = postdata["mobile"], username = postdata["mobile"])
            u.set_password(postdata["password"])

            u.nick_name = random_str(8)
            u.save()

            return res(0, u"注册成功")
        else:
            return res(-1, u"验证码错误！")


@api_view(['POST'])
def UserSms(request):
    """
    客户获取登陆验证码短信
    参数: mobile 手机号
    一个手机一分钟只能请求一次，否则返回错误
    """
    postdata = request.data
    if not postdata.has_key("mobile"):
        return res(-1, u"请输入手机号！")
    mobile = postdata["mobile"]
    if not phonecheck(mobile):
        return res(-1, u"手机号无效！")

    starttime = timezone.now() - datetime.timedelta(seconds = 60)
    queryset = SmsHist.objects.filter(mobile=postdata["mobile"]).filter(timestamp__gt=starttime)
    if queryset.exists():
        return res(-3, u"60秒内刚发送过验证码")

    codestr = random_numberstr(4).upper()
    msg = u"尊敬的用户，您的验证码是：" + codestr + u"，请在3分钟内输入【二十四城之家】"
    ret = send_sms(mobile, msg)
    if ret["error"] == 0:
        m = SmsHist(mobile=mobile, codestr=codestr)
        m.save()
        return res(0, u"发送成功")
    else:
        return res(-2, u"系统错误发送短信失败:" + str(ret["error"]) + u"-" + ret["msg"])


@api_view(['POST'])
def UserForgotPassword(request):
    """
    用户丢失密码找回：参数mobile 手机号 , code 验证码, password新密码
    请求该接口以前请获取验证码
    """
    postdata = request.data
    if not postdata.has_key("mobile"):
        return res(-1, u"请输入手机号！")
    if not phonecheck(postdata["mobile"]):
        return res(-1, u"手机号无效！")
    if not postdata.has_key("code"):
        return res(-1, u"请输入验证码！")
    if len(postdata["code"]) == 0:
        return res(-1, u"验证码无效！")
    if not passwordcheck(request.data["password"]):
        return res(-1, u"密码无效")

    queryset = UserProfile.objects.filter(mobile = postdata["mobile"])
    if queryset.exists():
        """校验验证码"""
        starttime = timezone.now() - datetime.timedelta(minutes = 3)
        queryset_code = SmsHist.objects.filter(mobile=postdata["mobile"]).\
            filter(timestamp__gt=starttime).\
            filter(codestr=postdata["code"].upper())

        if queryset_code.exists():
            """返回token"""
            u = queryset.all()[0]
            u.set_password(request.data['password'])
            u.save()

            return res(0, u"修改密码成功")
        else:
            return res(-1, u"验证码错误！")
    else:
        return res(-1, u"手机号未注册！")




class UserLogin(APIView):
    """用户登录: 参数mobile, password"""
    def post(self, request, format=None):
        if not request.data.has_key("mobile"):
            return res(-1, u"请输入账户！")
        if not request.data.has_key("password"):
            return res(-1, u"请输入密码！")
        if not passwordcheck(request.data["password"]):
            return res(-1, u"密码无效")



        username = request.data['mobile']
        password = request.data['password']
        user = auth.authenticate(username=username, password=password)

        if user is not None:
            # 更新最后登录时间
            user.last_login = timezone.now()
            user.save()

            serializer = UserProfileSerializer(user)
            data = serializer.data
            token = Token.objects.get_or_create(user=user)
            data["token"] = token[0].key

            return res(0, u"登陆成功", data)
        else:
            return res(-1, u"登录失败!")


class UserInfo(APIView):
    """客户信息管理: 访问所有接口必须带http头信息： Authorization: Token [登陆所返回token]"""
    permission_classes = (IsUserAuthenticated, )

    def get(self, request, format=None):
        """客户信息查询"""
        serializer = UserProfileSerializer(request.user)
        data = serializer.data
        token = Token.objects.get(user=request.user)
        data["token"] = token.key
        return res(0, u"", data)


    def put(self, request, format=None):
        """客户信息更改, 传入hash, 具体更改字段见模型"""
        serializer = UserProfileSerializer(request.user, data=request.data)
        if serializer.is_valid():
            if request.data.has_key('mobile'):
                """change username"""
                return res(-1, u"不能直接修改手机号！")

            serializer.save()
            data = serializer.data
            token = Token.objects.get(user=request.user)
            data["token"] = token.key
            return res(0, u"成功！", data);

        return res(-1, u"更新数据错误！", serializer.errors)



@api_view(['POST'])
@permission_classes((IsUserAuthenticated, ))
def UserUpdatePassword(request):
    """客户更改登陆密码:old_password带入老密码， new_password带入新密码"""
    if request.user.check_password(request.data["old_password"]):
        if not passwordcheck(request.data["new_password"]):
            return res(-1, u"新密码无效!")
        request.user.set_password(request.data['new_password'])
        request.user.save()
        return res(0, u"修改密码成功")
    else:
        return res(-1, u"旧密码错误！")


@api_view(['post'])
@permission_classes((IsUserAuthenticated, ))
def UserLogout(request):
    Token.objects.filter(user_id=request.user.id).delete()
    return res(0, '')


class RegionViewSet(MyReadOnlyModelViewSet):
    """查询区域"""
    serializer_class = RegionSerializer

    def get_queryset(self):
        queryset = Region.objects

        if self.request.query_params.has_key("parent_id"):
            queryset = queryset.filter(parent_id = self.request.query_params["parent_id"])

        if self.request.query_params.has_key("key"):
            queryset = queryset.filter(name__contains = self.request.query_params["key"])

        return queryset.all()


class CompanyViewSet(MyReadOnlyModelViewSet):
    """查询公司"""
    permission_classes = (IsUserAuthenticated, )
    serializer_class = CompanySerializer

    def get_queryset(self):
        queryset = Company.objects

        if self.request.query_params.has_key("region_id"):
            queryset = queryset.filter(region_id = self.request.query_params["region_id"])

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(Q(name__contains = key) | Q(address__contains = key) | Q(description__contains = key))
        
        return queryset.all()


class UserJobViewSet(MyReadOnlyModelViewSet):
    """查询人员岗位"""
    permission_classes = (IsUserAuthenticated, )
    serializer_class = UserJobSerializer

    def get_queryset(self):
        queryset = UserJob.objects

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter( Q(id = key) | Q(name__contains = key) )

        return queryset.all()


class DepartmentViewSet(MyReadOnlyModelViewSet):
    """查询部门"""
    permission_classes = (IsUserAuthenticated, )
    serializer_class = DepartmentSerializer

    def get_queryset(self):
        queryset = Department.objects

        if self.request.query_params.has_key("parent_id"):
            queryset = queryset.filter(parent_id = self.request.query_params["parent_id"])

        if self.request.query_params.has_key("company_id"):
            queryset = queryset.filter(company_id = self.request.query_params["company_id"])

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(name__contains = key)

        return queryset.all()


class CustomerProfileViewSet(MyModelViewSet):
    """客户管理"""
    permission_classes = (IsUserAuthenticated, )
    serializer_class = CustomerProfileSerializer

    def get_queryset(self):
        queryset = CustomerProfile.objects

        if self.request.query_params.has_key("sale_id"):
            queryset = queryset.filter(sale_id = self.request.query_params["sale_id"])

        if self.request.query_params.has_key("key"):
            key = self.request.query_params["key"]
            queryset = queryset.filter(name__contains = key)

        return queryset.all()





